package com.chc.web.notice.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chc.utils.CommonResult;
import com.chc.web.book.entity.Book;
import com.chc.web.notice.entity.SysNotice;
import com.chc.web.notice.entity.SysNoticeParm;
import com.chc.web.notice.service.SysNoticeService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

import static com.chc.utils.CommonResult.success;

/**
 * Created with IntelliJ IDEA
 *
 * @Author: chc
 * @Date: 2022/04/23/23:36
 * @Description:
 */
@RestController
@RequestMapping("/api/sysNotice")
public class SysNoticeController {

    @Autowired
    private SysNoticeService sysNoticeService;

    /**
     * 查询公告列表
     * */
    @GetMapping("/list")
    public CommonResult getNoticeList(SysNoticeParm parm){
        //构造条件
        QueryWrapper<SysNotice> query = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(parm.getTitle())) {
            query.lambda().eq(SysNotice::getTitle,parm.getTitle()).orderByDesc(SysNotice::getCreateTime);
        }
        //构造分页对象
        IPage<SysNotice> page = new Page<>();
        page.setCurrent(parm.getCurrentPage());
        page.setSize(parm.getPageSize());
        IPage<SysNotice> list = sysNoticeService.page(page, query);
        return CommonResult.success("查询成功",list);
    }

    /**
     * 添加公告列表
     * */
    @PostMapping
    @PreAuthorize("hasAuthority('sys:noticeList:add')")
    public CommonResult add(@RequestBody SysNotice sysNotice){
        sysNotice.setCreateTime(new Date());
        boolean save = sysNoticeService.save(sysNotice);
        if(save){
            return CommonResult.success("新增成功!");
        }
        return CommonResult.error("新增失败!");
    }

    /**
     * 编辑公告列表
     * */
    @PutMapping
    @PreAuthorize("hasAuthority('sys:noticeList:edit')")
    public CommonResult edit(@RequestBody SysNotice sysNotice){

        boolean save = sysNoticeService.updateById(sysNotice);
        if(save){
            return CommonResult.success("编辑成功!");
        }
        return CommonResult.error("编辑失败!");
    }

    /**
     * 删除公告列表
     * */
    @DeleteMapping("/{noticeId}")
    @PreAuthorize("hasAuthority('sys:noticeList:delete')")
    public CommonResult delete(@PathVariable("noticeId") Long noticeId){
        boolean b = sysNoticeService.removeById(noticeId);
        if(b){
            return CommonResult.success("删除成功!");
        }
        return CommonResult.error("删除失败!");
    }
}
